package com.woniu.springmybatis.service;

import com.woniu.springmybatis.entity.Account;
import com.woniu.springmybatis.mapper.AccountMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 * 账户信息类
 *
 * @author Taylor
 */
@Service("accountService")
@Transactional(readOnly = true)
public class AccountService {
    @Resource
    private AccountMapper accountMapper;

    /**
     * 账号登录验证
     *
     * @param username
     * @param password
     * @return
     */
    public Account validateUserInfor(String username, String password) {
        // 对密码进行加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        Example example = new Example(Account.class);
        // 组织查询条件---->WHERE username=? AND password=?
        example.createCriteria().andCondition("username=", username).andCondition("password=", password);
        // 使用通用mapper中的按条件查询
        List<Account> accounts = this.accountMapper.selectByExample(example);
        // 三元表达式，返回Account对象
        return accounts != null && !accounts.isEmpty() ? accounts.get(0) : null;
    }

    /**
     * 加密
     *
     * @param account
     * @return
     */
    @Transactional(readOnly = false)
    public boolean saveUserInfor(Account account) {
        // 进行密码加密
        account.setPassword(DigestUtils.md5DigestAsHex(account.getPassword().getBytes()));
        return this.accountMapper.insert(account) > 0;
    }

    public List<Account> findAll() {
        return this.accountMapper.selectAll();

    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    public boolean deleteById(int id) {
        return this.accountMapper.deleteByPrimaryKey(id) > 0;
    }
}
